'use strict';
const uniID = require('uni-id-common')
const ASE= require('ase')
exports.main = async (event, context) => {
	if (event.uniIdToken == null) {
		return []
	}
	const uniIDIns = uniID.createInstance({
		context: context,
	})
	const res = await uniIDIns.checkToken(event.uniIdToken)
	const db = uniCloud.databaseForJQL({
		event,
		context
	});
	db.setUser({
			role: ['admin']
		})
		if(res.uid==null){
			return null
		}
		await db.collection("uni-id-users").where({_id:res.uid}).update({last_login_date:new Date().getTime()})
	// 消息数量
	let {data:msg} = await db.collection("message").where({
		to: res.uid,
		mode: '未读'
	}).get();
	// 计算下载数与文件数
	const useritem = await db.collection("item").where({
		user_id: res.uid,
		otherlink:false,
	}).groupBy('a').groupField(
		'sum(size) as size, sum(down) as down').get()
		const item = await db.collection("item").where("type!='file'&&user_id=='"+res.uid+"'").count()
	if(useritem.data.length>0){
		var down = useritem.data[0].down
		var itemnum=item.total
		var size=useritem.data[0].size
	}else{
		var down =0
		var itemnum=0
		var size=0
	}

	//获取用户信息
	const userinfo = await db.collection("uni-id-users").where({
		_id: res.uid
	}).field({
		avatar: true,
		email: true,
		nickname: true,
		username: true,
		limit:true,
		state:true,
		vip:true,
		uid:true,
identity:true
	}).get();
	var storage;
	if(userinfo.data[0].limit<size){
		storage={msg:"超出",code:400,limit:userinfo.data[0].limit,bytes:size}
	}else{
		storage={msg:"未超出",code:200,limit:userinfo.data[0].limit,bytes:size}
	}
	return ASE.AES.encrypt(JSON.stringify({
			userinfo:userinfo.data[0],
			msg: msg.length,
			item: itemnum,
			down: down,
			storage:storage
		}),'yclycl1314520520','9740022097400220')
};